import { useState, useEffect } from 'react';
import { createProduct, updateProduct, getImageUrl } from '../services/pocketBaseService';

function ProductForm({ product, onSuccess, onCancel }) {
  const [formData, setFormData] = useState({
    product_name: '',
    product_desc: '',
    points_score: 0,
    cash_price: '',
    stock: 0,
    sold: 0,
    status: true,
    image_file: null,
    sold_strategy: '只需积分', // 新增字段，默认只需积分
    sold_strategy_num: ''      // 新增字段，默认空
  });
  const [preview, setPreview] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 如果是编辑模式，加载商品数据
  useEffect(() => {
    if (product) {
      setFormData({
        product_name: product.product_name || '',
        product_desc: product.product_desc || '',
        points_score: product.points_score || 0,
        cash_price: product.cash_price || '',
        stock: product.stock || 0,
        sold: product.sold || 0,
        status: product.status !== undefined ? product.status : true,
        image_file: null, // 文件输入需要用户重新选择
        sold_strategy: product.sold_strategy || '只需积分',
        sold_strategy_num: product.sold_strategy_num || ''
      });

      // 设置图片预览
      if (product.image_file) {
        setPreview(getImageUrl(null, product.id, product.image_file));
      }
    }
  }, [product]);

  // 处理表单字段变更
  const handleChange = (e) => {
    const { name, value, type, checked, files } = e.target;
    
    if (type === 'file') {
      // 处理文件上传
      const file = files[0];
      if (file) {
        setFormData(prev => ({ ...prev, [name]: file }));
        
        // 创建预览URL
        const fileReader = new FileReader();
        fileReader.onload = () => {
          setPreview(fileReader.result);
        };
        fileReader.readAsDataURL(file);
      }
    } else if (type === 'checkbox') {
      setFormData(prev => ({ ...prev, [name]: checked }));
    } else if (name === 'points_score' || name === 'stock' || name === 'sold' || name === 'sold_strategy_num') {
      // sold_strategy_num 也要转数字
      const numberValue = parseInt(value) || 0;
      setFormData(prev => ({ ...prev, [name]: numberValue }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  // 提交表单
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      let submitData = { ...formData };
      // 如果是“只需积分”，补多少元设为0
      if (submitData.sold_strategy === '只需积分') {
        submitData.sold_strategy_num = 0;
      }
      let result;
      if (product) {
        // 更新商品
        result = await updateProduct(product.id, submitData);
      } else {
        // 创建商品
        result = await createProduct(submitData);
      }

      if (result.success) {
        onSuccess();
      } else {
        setError(result.error || '保存商品失败');
      }
    } catch (err) {
      setError('提交表单时发生错误');
      console.error('商品表单提交错误:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          {error}
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          商品名称 <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          name="product_name"
          value={formData.product_name}
          onChange={handleChange}
          required
          className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          商品描述
        </label>
        <textarea
          name="product_desc"
          value={formData.product_desc}
          onChange={handleChange}
          rows={3}
          className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            积分 <span className="text-red-500">*</span>
          </label>
          <input
            type="number"
            name="points_score"
            value={formData.points_score}
            onChange={handleChange}
            required
            min="0"
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            现金价格 <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            name="cash_price"
            value={formData.cash_price}
            onChange={handleChange}
            required
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            库存数量 <span className="text-red-500">*</span>
          </label>
          <input
            type="number"
            name="stock"
            value={formData.stock}
            onChange={handleChange}
            required
            min="0"
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            已售数量
          </label>
          <input
            type="number"
            name="sold"
            value={formData.sold}
            onChange={handleChange}
            min="0"
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>
      </div>

      <div>
        <div className="flex items-center">
          <input
            type="checkbox"
            name="status"
            id="status"
            checked={formData.status}
            onChange={handleChange}
            className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
          />
          <label htmlFor="status" className="ml-2 block text-sm text-gray-900">
            上架状态
          </label>
        </div>
        <p className="text-xs text-gray-500 mt-1">
          选中表示商品已上架，可见可购买；未选中表示商品已下架。
        </p>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          商品图片
        </label>
        <input
          type="file"
          name="image_file"
          accept="image/*"
          onChange={handleChange}
          className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100"
        />
        {preview && (
          <div className="mt-2">
            <p className="text-sm text-gray-500 mb-1">预览:</p>
            <div className="relative">
              <img 
                src={preview} 
                alt="商品预览" 
                className="h-32 w-auto object-contain rounded border border-gray-200 shadow-sm" 
                onError={(e) => {
                  e.target.style.display = 'none';
                  e.target.nextSibling.style.display = 'flex';
                }}
              />
              <div className="hidden h-32 w-32 bg-gray-200 rounded flex items-center justify-center text-sm text-gray-500 border border-gray-200">
                图片加载失败
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            销售策略 <span className="text-red-500">*</span>
          </label>
          <select
            name="sold_strategy"
            value={formData.sold_strategy}
            onChange={handleChange}
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          >
            <option value="只需积分">只需积分</option>
            <option value="积分外补">积分外补</option>
          </select>
        </div>
        {formData.sold_strategy === '积分外补' && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              补多少元 <span className="text-red-500">*</span>
            </label>
            <input
              type="number"
              name="sold_strategy_num"
              value={formData.sold_strategy_num}
              onChange={handleChange}
              min="0"
              required={formData.sold_strategy === '积分外补'}
              className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
        )}
      </div>

      <div className="flex justify-end space-x-3 pt-4">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          取消
        </button>
        <button
          type="submit"
          disabled={loading}
          className={`px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white ${
            loading ? 'bg-indigo-400' : 'bg-indigo-600 hover:bg-indigo-700'
          } focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500`}
        >
          {loading ? '保存中...' : '保存商品'}
        </button>
      </div>
    </form>
  );
}

export default ProductForm;